#include "database.h"
#include"stack.h"
#include <stdio.h>
#include <string.h>

// 查询用户是否已有根目录
static int get_root_id_if_exists(MYSQL* conn, const char* user_name, int* root_id_out) {
    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) return -1;

    const char* sql = "SELECT id FROM nodes WHERE name='/' AND p_id=-1 AND user_name=?";
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND bind[1];
    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void*)user_name;
    bind[0].buffer_length = strlen(user_name);

    if (mysql_stmt_bind_param(stmt, bind) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    if (mysql_stmt_execute(stmt) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND result[1];
    memset(result, 0, sizeof(result));
    int root_id;
    result[0].buffer_type = MYSQL_TYPE_LONG;
    result[0].buffer = (void*)&root_id;

    if (mysql_stmt_bind_result(stmt, result) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    int fetch_status = mysql_stmt_fetch(stmt);
    mysql_stmt_close(stmt);

    if (fetch_status == 0) {
        *root_id_out = root_id;
        return 0;  // 找到了
    } else {
        return -1; // 未找到
    }
}

// 主函数：初始化用户路径（已有则复用）
int init_user_root_directory(MYSQL* conn, const char* user_name, DirStack* stack) {
    int root_id;
    if (get_root_id_if_exists(conn, user_name, &root_id) == 0) {
        init_stack(stack);
        return push(stack, root_id);
    }

    // 没有则创建根目录
    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) return -1;

    const char* sql = "INSERT INTO nodes (name, user_name, p_id, is_dir) VALUES ('/', ?, -1, 1)";
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND bind[1];
    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void*)user_name;
    bind[0].buffer_length = strlen(user_name);

    if (mysql_stmt_bind_param(stmt, bind) != 0 || mysql_stmt_execute(stmt) != 0) {
        mysql_stmt_close(stmt);
        return -1;
    }

    my_ulonglong inserted_id = mysql_stmt_insert_id(stmt);
    if (inserted_id == 0) {
        inserted_id = mysql_insert_id(conn); // fallback
    }
    mysql_stmt_close(stmt);

    if (inserted_id == 0) return -1;

    init_stack(stack);
    return push(stack, (int)inserted_id);
}

